<template>
  <div class="case-management-container">
    <!-- 案件列表表格 -->
    <el-table
      ref="multipleTableRef"
      :data="formattedTableData"
      row-key="id"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <el-table-column property="caseNo" label="案件编号" width="180" label-align="center" />
      <el-table-column property="caseTitle" label="案件名称" width="180" label-align="center" />
      
      <!-- 案件类型（枚举映射） -->
      <el-table-column label="案件类型" width="120" label-align="center">
        <template #default="scope">
          {{ scope.row.type }}
        </template>
      </el-table-column>
      
      <!-- 案件状态（枚举映射） -->
      <el-table-column label="案件状态" width="120" label-align="center">
        <template #default="scope">
          {{ scope.row.status }}
        </template>
      </el-table-column>
      
      <el-table-column property="lawyerId" label="受理律师" width="120" label-align="center">
        <template #default="scope">
          {{ scope.row.lawyerId || '未分配' }}
        </template>
      </el-table-column>
      
      <el-table-column label="操作" label-align="center">
        <template #default="scope">
          <el-button type="info" size="mini" @click="handleViewDetail(scope.row.caseNo)">详情</el-button>
          <el-button type="primary" size="mini">更新状态</el-button>
          <el-button type="success" size="mini" @click="handleExportMaterial(scope.row.caseNo)">导出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 案件详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="案件详情"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="detail-content">
        <!-- 基础信息 -->
        <el-form
          :model="detailInfo"
          label-width="120px"
          class="base-info-form"
          disabled
        >
          <el-form-item label="案件编号">
            <el-input :value="detailInfo.caseNo" readonly />
          </el-form-item>
          
          <el-form-item label="案件名称">
            <el-input :value="detailInfo.caseTitle" readonly />
          </el-form-item>
          
          <el-form-item label="案件类型">
            <el-input :value="caseTypeMap[detailInfo.type] || detailInfo.type" readonly />
          </el-form-item>
          
          <el-form-item label="案件状态">
            <el-input :value="caseStatusMap[detailInfo.status] || detailInfo.status" readonly />
          </el-form-item>
          
          <el-form-item label="申请人ID">
            <el-input :value="detailInfo.userId" readonly />
          </el-form-item>
          
          <el-form-item label="受理律师">
            <el-input :value="detailInfo.lawyerId || '未分配'" readonly />
          </el-form-item>
          
          <el-form-item label="申请时间">
            <el-input :value="formatDateTime(detailInfo.applyTime)" readonly />
          </el-form-item>
          
          <el-form-item label="案情描述">
            <el-input
              :value="detailInfo.description"
              type="textarea"
              :rows="4"
              readonly
            />
          </el-form-item>
        </el-form>

        <!-- 案件材料 -->
        <div class="materials-section">
          <h3 class="section-title">案件材料（共 {{ materialList.length }} 项）</h3>
          
          <div 
            class="material-item" 
            v-for="(material, index) in materialList" 
            :key="material.id || index"
          >
            <el-form
              :model="material"
              label-width="120px"
              class="material-form"
              disabled
            >
              <el-form-item label="材料类型">
                <el-input 
                  :value="getMaterialTypeText(material.type)" 
                  readonly 
                />
              </el-form-item>
              
              <el-form-item label="材料名称">
                <el-input :value="material.materialName || '未命名'" readonly />
              </el-form-item>
              
              <el-form-item label="上传时间">
                <el-input :value="formatDateTime(material.uploadTime)" readonly />
              </el-form-item>
              
              <el-form-item label="审核状态">
                <el-input :value="getAuditStatusText(material.auditStatus)" readonly />
              </el-form-item>
              
              <el-form-item label="材料地址">
                <el-input :value="material.url" readonly class="url-input" />
              </el-form-item>
            </el-form>
          </div>
          
          <div v-if="materialList.length === 0" class="no-materials">
            暂无案件材料
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { operateCaseApi } from '../../api/operateCase/index';

// 表格相关
const multipleTableRef = ref(null);
const multipleSelection = ref([]);
const tableData = ref([]);

// 详情对话框相关
const dialogVisible = ref(false);
const detailInfo = ref({}); // 案件基础信息
const materialList = ref([]); // 案件材料列表

// 枚举映射
const caseStatusMap = {
  'PENDING': '待受理',
  'PEVIEWING': '审核中',
  'ASSIGNED': '已分配',
  'IN_PROCESS': '处理中',
  'COMPLETED': '已完成',
  'CLOSED': '已拒绝'
};

const caseTypeMap = {
  'CIVIL': '民事案件',
  'CRIMINAL': '刑事案件',
  'ADMINISTRATIVE': '行政案件',
  'OTHER': '其他案件'
};

const materialTypeMap = {
  'ID_CARD': '身份证',
  'COMPLAINT': '起诉状',
  'VIDEO': '视频',
  'IMAGE': '图片',
  'OTHER': '其他'
};

const auditStatusMap = {
  'DRAFT': '草稿',
  'AUDITED': '已审核',
  'REJECTED': '未通过'
};

// 格式化表格数据
const formattedTableData = computed(() => {
  return tableData.value.map(row => ({
    ...row,
    type: caseTypeMap[row.type] || `未知类型(${row.type})`,
    status: caseStatusMap[row.status] || `未知状态(${row.status})`,
    materialCount: row.materialCount || 0
  }));
});

// 工具函数：格式化时间
const formatDateTime = (timeStr) => {
  if (!timeStr) return '';
  const date = new Date(timeStr);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-');
};

// 工具函数：获取材料类型文本
const getMaterialTypeText = (type) => {
  return materialTypeMap[type] || `未知类型(${type})`;
};

// 工具函数：获取审核状态文本
const getAuditStatusText = (status) => {
  return auditStatusMap[status] || `未知状态(${status})`;
};

// 表格选择逻辑
const selectable = (row) => ![1, 2].includes(row.id);

const toggleSelection = (rows, ignoreSelectable) => {
  if (rows && multipleTableRef.value) {
    rows.forEach(row => {
      multipleTableRef.value.toggleRowSelection(row, undefined, ignoreSelectable);
    });
  } else if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection();
  }
};

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

// 请求参数
const searchParams = ref({
  caseStatus: null,
  type: null,
  lawyerId: '',
  page: '1',
  pageSize: '10'
});

// 获取案件列表
const fetchCaseList = async () => {
  const loading = ElLoading.service({ text: '加载中...' });
  try {
    const res = await operateCaseApi.getCaseList(searchParams.value);
    tableData.value = res.data.legalCaseList.map(item => ({
      ...item,
      // 计算材料数量（适配后端返回结构）
      materialCount: item.caseMaterialList?.length || 0
    }));
    return res;
  } catch (error) {
    ElMessage.error('获取案件列表失败');
    return Promise.reject(error);
  } finally {
    loading.close();
  }
};

// 查看案件详情
const handleViewDetail = async (caseNo) => {
  const loading = ElLoading.service({ text: '加载详情...' });
  try {
    const res = await operateCaseApi.getCaseDetail(caseNo);
    detailInfo.value = res.data.legalCase || {};
    materialList.value = res.data.caseMaterialList || [];
    dialogVisible.value = true;
    return res;
  } catch (error) {
    ElMessage.error('获取案件详情失败');
    return Promise.reject(error);
  } finally {
    loading.close();
  }
};

// 导出案件材料
const handleExportMaterial = async (caseNo) => {
  try {
    // 直接跳转 GET 接口，让浏览器处理下载
    window.open(`/api/export?case_no=${caseNo}`, '_blank'); 
    ElMessage.success('导出请求已发送，浏览器将自动下载');
  } catch (error) {
    ElMessage.error('导出失败，请检查网络或联系管理员');
  }
};

// 页面初始化
onMounted(() => {
  fetchCaseList();
});
</script>

<style scoped>
.case-management-container {
  padding: 20px;
}

.el-table {
  margin-top: 10px;
}

/* 详情对话框样式 */
.detail-content {
  padding: 10px 0;
}

.base-info-form {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.materials-section {
  margin-top: 15px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  color: #333;
}

.material-item {
  background: #f9f9f9;
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 12px;
}

.url-input {
  font-size: 12px;
  color: #666;
  word-break: break-all;
}

.no-materials {
  text-align: center;
  padding: 30px;
  color: #999;
  background: #f9f9f9;
  border-radius: 6px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .el-form-item__label {
    width: 100px !important;
  }
  
  .url-input {
    font-size: 11px;
  }
}
</style>
